package cn.bwq.datawebsocket.core.server;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@Service
@ServerEndpoint("/api/ws/{sid}")
public class WebSocketServer {

    static final Logger log = LoggerFactory.getLogger(WebSocketServer.class);

    // 当前在线连接数
    private static int onlineCount = 0;
    // 存放每个客户端对应的MyWebSocket对象
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<>();
    private Session session;
    // 接收sid
    private String sid = "";

    /**
     * 监听连接建立成功
     *
     * @param session 会话
     * @param sid     客户端sid
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("sid") String sid) {
        this.session = session;
        webSocketSet.add(this);
        this.sid = sid;
        addOnlineCount();
        try {
            sendMessage("connect_success");
            log.info("有新窗口开始监听:{}, 当前在线人数为:{}", sid, getOnlineCount());
        } catch (Exception e) {
            log.error("websocket IO Exception");
        }
    }

    /**
     * 监听连接关闭
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);
        subOnlineCount();
        log.info("释放的sid为：{}", sid);
        log.info("连接{}关闭！当前在线人数为:{}", sid, getOnlineCount());
    }

    /**
     * 监听客户端消息
     * @param message 客户端消息
     * @param session 会话
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("收到客户端[{}]的信息:{}", sid, message);
        // 群发消息
        for (WebSocketServer wss : webSocketSet) {
            try {
                if (!ObjectUtils.nullSafeEquals(wss, this)) {
                    wss.sendMessage(message);
                }
            } catch (IOException e) {
                // don't do something
            }
        }
    }

    /**
     * 错误监听
     * @param session 会话
     * @param error 错误
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误");
        error.printStackTrace();
    }

    /**
     * 服务器主动推送消息
     * @param message 消息
     * @throws IOException 异常
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    /**
     * 群发消息
     * @param message 消息
     * @param sid sid不为空则指定推送；为null则群发消息
     * @throws IOException 异常
     */
    public static void sendInfo(String message, @PathParam("sid") String sid) throws IOException {
        for (WebSocketServer wss : webSocketSet) {
            try {
                if (sid != null) {
                    if (ObjectUtils.nullSafeEquals(wss.sid, sid)) {
                        log.info("推送消息到{}，推送内容:{}", sid, message);
                        wss.sendMessage(message);
                    }
                } else {
                    wss.sendMessage(message);
                }
            } catch (IOException e) {
                // don't do something
            }
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }

    public static CopyOnWriteArraySet<WebSocketServer> getWebSocketSet() {
        return webSocketSet;
    }
}
